<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="goods in shopcartList" :key="goods.skuId">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="goods.isChecked"
              @click="getChangeOneChecked(goods)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="goods.imgUrl" />
            <div class="item-msg">{{ goods.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ goods.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              @click="changeNum('sub', -1, goods)"
              class="mins"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              @change="changeNum('input', $event.target.value * 1, goods)"
              :value="goods.skuNum"
              minnum="1"
              class="itxt"
            />
            <a
              href="javascript:void(0)"
              @click="changeNum('add', 1, goods)"
              class="plus"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ goods.skuPrice * goods.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a class="sindelet" @click="getDeleteOne(goods)">删除</a>
            <br />
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool" v-if="shopcartList.length">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="chooseAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="getDeleteChecked">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ chooseNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <!-- <a class="sum-btn" href="###" target="_blank">结算</a> -->
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>
    <h1 v-else style="height: 100px; text-align: center; line-height: 100px">
      现在购物车空空,请添加心仪得商品！
    </h1>
  </div>
</template>

<script>
import throttle from "lodash/throttle";
import { mapState } from "vuex";
export default {
  name: "ShopCart",
  mounted() {
    this.getShopcartList();
  },
  methods: {
    getShopcartList() {
      this.$store.dispatch("getShopcartList");
    },
    // 修改商品数量
    changeNum: throttle(
      async function (flag, disNum, goods) {
        // flag 区分用户是那种方式要去修改数量的
        // disNum 变化的量(加和减) 输入而言是最新的数量
        // goods 是某个商品 回头可以用到他的skuId

        if (flag === "add") {
          //加
          // 我不删  但是删了也没有影响
        } else if (flag === "sub") {
          //减
          // 如果当前数量是1 不能再让他-1了  让他变化的量是0  不加也不减
          if (goods.skuNum === 1) {
            disNum = 0;
          }
        } else {
          //输入
          // 如果用户输入的最新的小于1 之前原先是什么现在还是什么 不增不减
          // if(disNum < 1){ //输入的小于1的
          //   disNum = 0
          // }else{ //正常输入的  获取变量的量  新值-旧值
          //   disNum = disNum - goods.skuNum
          // }
          disNum = disNum < 1 ? 0 : disNum - goods.skuNum;
        }
        // 要去发送请求 需要带上商品id以及变化的数量
        try {
          // 让数据库当中的数据更新
          await this.$store.dispatch("getAddShopcart", {
            skuId: goods.skuId,
            skuNum: disNum,
          });
          // 咱的前端页面也应该展示最新数据
          this.getShopcartList();
        } catch (error) {
          alert("更新商品数量失败了!");
        }
      },
      2000,
      { trailing: false }
    ),
    // 修改单个选中状态
    async getChangeOneChecked(goods) {
      // 不能直接取反 因为要求传递0或者是1  取反就获取到了布尔值
      // 原先是0 传1  原先是1 传0
      try {
        await this.$store.dispatch("getChangeOneChecked", {
          skuId: goods.skuId,
          isChecked: goods.isChecked ? 0 : 1,
        });
        // 获取最新状态
        this.getShopcartList();
      } catch (e) {
        alert("修改单个选中状态失败");
      }
    },
    // 删除单个
    async getDeleteOne(goods) {
      try {
        await this.$store.dispatch("getDeleteOne", goods.skuId);
        // 重新发送请求
        this.getShopcartList();
      } catch (error) {
        alert("删除单个商品失败了");
      }
    },
    // 删除选中
    async getDeleteChecked() {
      let skuIdList = [];
      this.shopcartList.forEach((item) => {
        if (item.isChecked) {
          skuIdList.push(item.skuId);
        }
      });
      try {
        await this.$store.dispatch("getDeleteChecked", skuIdList);
        // 重新获取最新列表
        this.getShopcartList();
      } catch (error) {
        alert("删除选中得商品失败");
      }
    },
  },
  computed: {
    ...mapState({
      shopcartList: (state) => state.shopcart.shopcartList,
    }),
    // 选中的商品数量
    chooseNum() {
      let num = 0;
      this.shopcartList.forEach((item) => {
        if (item.isChecked) {
          //选中的累加自身的数量 不是恒加1!!
          num += item.skuNum;
        }
      });
      return num;
    },
    // 选中的总价
    totalPrice() {
      return this.shopcartList.reduce((prev, item, index) => {
        if (item.isChecked) {
          prev += item.skuNum * item.skuPrice;
        }
        return prev;
      }, 0);
    },
    // 全选
    chooseAll: {
      get() {
        return this.shopcartList.every((item) => item.isChecked);
      },
      async set(newVal) {
        // console.log(newVal)
        let skuIdList = [];
        // 如果newVal和每一项的isChecked不同 那么才需要放入数组中
        this.shopcartList.forEach((item) => {
          // 不能用!==
          if (item.isChecked != newVal) {
            skuIdList.push(item.skuId);
          }
        });
        try {
          await this.$store.dispatch("getChangeAllChecked", {
            isChecked: newVal ? 1 : 0,
            skuIdList,
          });
          // 重新发送请求
          this.getShopcartList();
        } catch (error) {
          alert("更新多个选中状态失败!!!");
        }
      },
    },
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
</style>
